package com.shop.task;

import com.shop.entity.Orders;
import com.shop.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务类
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 处理超时订单（超过15min未支付）每1min执行一次
     * 将订单状态  待支付————>已取消
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrders() {
        log.info("定时任务处理超时订单：{}", LocalDateTime.now());
        //当前时间-15min
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //查状态是未支付的订单
        //select * from orders where status = #{status} and order_time < (当前时间-15min)
        List<Orders> orders = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        if (orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("超时未支付，自动取消");
                order.setCancelTime(LocalDateTime.now());

                orderMapper.update(order);
            }
        }

    }

    /**
     * 处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点触发
    public void processDeliveryOrder() {
        log.info("定时任务处理派送中的订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);

        if(orders != null && orders.size() > 0) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
//                order.setCancelReason("超时未支付，自动取消");
//                order.setCancelTime(LocalDateTime.now());

                orderMapper.update(order);
            }
        }
    }
}
